package com.example.show_auto.ui.pages

import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.border
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

import com.example.show_auto.viewmodel.MainViewModel
import com.example.show_auto.data.UltimateDataStorage
import com.example.show_auto.data.MultiUserDataManager
import com.example.show_auto.data.PersonalDataManager
import com.example.show_auto.data.SettingsStorage
import com.example.show_auto.data.Chef
import com.example.show_auto.data.Skill
import com.example.show_auto.ui.utils.DeviceCompatibility
import com.example.show_auto.ui.utils.OppoCompatibilityFix
import com.example.show_auto.ui.theme.getChefBoxCompatibleCardColors
import com.example.show_auto.ui.theme.getDarkGreyBackgroundColor
import com.example.show_auto.ui.components.UserSwitchDialog
import com.example.show_auto.ui.components.UserActionChoiceDialog
import com.example.show_auto.ui.components.UserNameInputDialog
import androidx.compose.ui.platform.LocalContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
import android.app.Application

/**
 * 个人数据页面
 * 用于导入和管理个人数据
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PersonalDataPage(
    viewModel: MainViewModel,
    onMenuClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    var codeInput by remember { mutableStateOf(TextFieldValue("")) }
    val uiState by viewModel.uiState.collectAsState()
    val context = LocalContext.current
    val multiUserDataManager = remember { MultiUserDataManager(context) }
    
    // 弹窗状态管理
    var showUserSwitchDialog by remember { mutableStateOf(false) }
    var showUserActionDialog by remember { mutableStateOf(false) }
    var showUserNameInputDialog by remember { mutableStateOf(false) }
    
    // 用户数据状态
    var allUsers by remember { mutableStateOf<List<MultiUserDataManager.UserData>>(emptyList()) }
    var currentUser by remember { mutableStateOf<String?>(null) }
    
    // 加载用户数据
    LaunchedEffect(Unit) {
        allUsers = multiUserDataManager.getAllUsers()
        currentUser = multiUserDataManager.getCurrentUser()
    }
    
    // 监听ViewModel中的数据变化，确保页面状态与ViewModel同步
    LaunchedEffect(uiState.isCodeValid, uiState.validationCode) {
        // 当ViewModel的状态改变时，重新同步用户状态
        val newCurrentUser = multiUserDataManager.getCurrentUser()
        if (newCurrentUser != currentUser) {
            currentUser = newCurrentUser
            allUsers = multiUserDataManager.getAllUsers()
        }
    }
    
    // 监听自动读取已修炼的状态并重置标志
    LaunchedEffect(uiState.shouldAutoLoadUltimate) {
        if (uiState.shouldAutoLoadUltimate) {
            // 延迟重置标志，确保PersonalDataConfigSection有时间响应
            delay(500) // 比PersonalDataConfigSection的延迟时间长
            viewModel.resetAutoLoadUltimateFlag()
        }
    }
    
    OppoCompatibilityFix.FixedLayoutContainer(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部应用栏
        TopAppBar(
            title = { 
                Text(
                    text = "个人数据",
                    fontWeight = FontWeight.Medium
                )
            },
            navigationIcon = {
                IconButton(onClick = onMenuClick) {
                    Icon(
                        imageVector = Icons.Default.Menu,
                        contentDescription = "菜单"
                    )
                }
            },
            actions = {
                // 切换用户按钮
                TextButton(
                    onClick = { showUserSwitchDialog = true }
                ) {
                    Text(
                        text = "切换用户",
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )
        
        // 页面内容
        Column(
            modifier = Modifier
                .fillMaxSize()
                .let {
                    if (OppoCompatibilityFix.isProblematicOppoDevice()) {
                        it.verticalScroll(rememberScrollState()).fillMaxSize()
                    } else {
                        it.verticalScroll(rememberScrollState())
                    }
                }
                .padding(OppoCompatibilityFix.getFixedSpacing(16.dp)),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {

            
            Spacer(modifier = Modifier.height(OppoCompatibilityFix.getFixedSpacing(5.dp)))
            
            // 校验码输入区域
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = OppoCompatibilityFix.getFixedCardColors()
            ) {
                Column(
                    modifier = Modifier.padding(OppoCompatibilityFix.getFixedSpacing(16.dp))
                ) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                            text = "导入新数据",
                        fontSize = 16.sp,
                            fontWeight = FontWeight.Medium
                    )
                    
                        // 显示数据导入状态
                    if (uiState.isCodeValid) {
                            Spacer(modifier = Modifier.width(12.dp))
                        Row(
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                imageVector = Icons.Default.CheckCircle,
                                contentDescription = "已验证",
                                tint = MaterialTheme.colorScheme.primary,
                                    modifier = Modifier.size(16.dp)
                            )
                                Spacer(modifier = Modifier.width(4.dp))
                            Text(
                                    text = "已导入: ${uiState.validationCode}",
                                    fontSize = 12.sp,
                                    color = MaterialTheme.colorScheme.primary
                            )
                        }
                    }
                }
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    OutlinedTextField(
                        value = codeInput,
                        onValueChange = { codeInput = it },
                        label = { Text("请输入官方校验码") },
                        placeholder = { Text("校验码") },
                        modifier = Modifier
                            .fillMaxWidth()
                            .pointerInput(Unit) {
                                detectTapGestures(
                                    onLongPress = {
                                        // 长按全选
                                        if (codeInput.text.isNotEmpty()) {
                                            codeInput = codeInput.copy(
                                                selection = TextRange(0, codeInput.text.length)
                                            )
                                        }
                                    },
                                    onDoubleTap = {
                                        // 双击全选
                                        if (codeInput.text.isNotEmpty()) {
                                            codeInput = codeInput.copy(
                                                selection = TextRange(0, codeInput.text.length)
                                            )
                                        }
                                    }
                                )
                            },
                        singleLine = true,
                        enabled = !uiState.isValidating
                    )
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    Button(
                        onClick = {
                            // 始终弹窗让用户选择操作
                            showUserActionDialog = true
                        },  
                        modifier = Modifier.fillMaxWidth(),
                        enabled = !uiState.isValidating
                    ) {
                        if (uiState.isValidating) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                color = MaterialTheme.colorScheme.onPrimary
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                        }
                        Text(if (uiState.isValidating) "导入中..." else "导入个人数据")
                    }
                }
            }
            
            // 错误信息显示
            uiState.error?.let { error ->
                Spacer(modifier = Modifier.height(16.dp))
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.errorContainer
                    )
                ) {
                    Row(
                        modifier = Modifier.padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.Warning,
                            contentDescription = "错误",
                            tint = MaterialTheme.colorScheme.onErrorContainer
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = error,
                            color = MaterialTheme.colorScheme.onErrorContainer
                        )
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(24.dp))

            // 个人数据配置区域 - 即使校验码过期也显示之前保存的数据
                PersonalDataConfigSection(
                    viewModel = viewModel,
                    shouldAutoLoadUltimate = uiState.shouldAutoLoadUltimate
                )
                Spacer(modifier = Modifier.height(24.dp))

            // 使用说明
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                )
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text(
                        text = "使用说明",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = "• 输入白菜菊花码可导入您的游戏数据\n" +
                                "• 导入数据只计算满阶满级厨师\n" +
                                "• 应用重启会重新获取最新游戏数据\n" +
                                "• 如遇网络问题，请检查网络连接后重试",
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        lineHeight = 20.sp
                    )
                }
            }
        }
    }
    
    // 用户切换弹窗
    if (showUserSwitchDialog) {
        UserSwitchDialog(
            users = allUsers,
            currentUser = currentUser,
            onSwitchUser = { selectedUser ->
                viewModel.switchToUser(selectedUser, multiUserDataManager) {
                    // 切换成功后刷新状态
                    currentUser = multiUserDataManager.getCurrentUser()
                    
                    // 直接触发读取已修炼
                    viewModel.triggerAutoLoadUltimateSkills()
                }
                showUserSwitchDialog = false
            },
            onDeleteUser = { userToDelete ->
                multiUserDataManager.deleteUser(userToDelete.userName)
                // 刷新用户列表
                allUsers = multiUserDataManager.getAllUsers()
                currentUser = multiUserDataManager.getCurrentUser()
                
                // 如果删除的是当前用户，清空当前数据
                if (userToDelete.userName == currentUser) {
                    viewModel.clearCurrentUserData()
                }
            },
            onUpdateUserName = { oldName, newName ->
                // 仅更新用户名，保持所有其他数据不变
                if (multiUserDataManager.updateUserName(oldName, newName)) {
                    // 如果修改的是当前用户，更新当前用户变量
                    if (oldName == currentUser) {
                        currentUser = newName
                    }
                    // 刷新用户列表
                    allUsers = multiUserDataManager.getAllUsers()
                }
            },
            onReorderUsers = { reorderedUsers ->
                // 保存用户重新排序后的顺序，排除当前用户（当前用户永远在第一位）
                val currentUserName = multiUserDataManager.getCurrentUser()
                val orderedUserNames = reorderedUsers
                    .filter { it.userName != currentUserName }  // 排除当前用户
                    .map { it.userName }
                multiUserDataManager.saveUserOrder(orderedUserNames)
                // 刷新用户列表
                allUsers = multiUserDataManager.getAllUsers()
            },
            onDismiss = { showUserSwitchDialog = false },
            multiUserDataManager = multiUserDataManager
        )
    }
    
    // 用户操作选择弹窗
    if (showUserActionDialog) {
        UserActionChoiceDialog(
            currentUserName = currentUser,
            onNewUser = {
                showUserActionDialog = false
                showUserNameInputDialog = true
            },
            onUpdateCurrent = {
                showUserActionDialog = false
                // 更新当前用户数据
                viewModel.validateCodeForMultiUser(
                    code = codeInput.text.trim(),
                    isNewUser = false,
                    userName = currentUser ?: "默认用户",
                    multiUserDataManager = multiUserDataManager,
                    onSuccess = {
                        // 刷新用户列表
                        allUsers = multiUserDataManager.getAllUsers()
                        currentUser = multiUserDataManager.getCurrentUser()
                    }
                )
            },
            onDismiss = { showUserActionDialog = false }
        )
    }
    
    // 用户名输入弹窗
    if (showUserNameInputDialog) {
        UserNameInputDialog(
            onConfirm = { userName ->
                showUserNameInputDialog = false
                // 创建新用户
                viewModel.validateCodeForMultiUser(
                    code = codeInput.text.trim(),
                    isNewUser = true,
                    userName = userName,
                    multiUserDataManager = multiUserDataManager,
                    onSuccess = {
                        // 刷新用户列表
                        allUsers = multiUserDataManager.getAllUsers()
                        currentUser = multiUserDataManager.getCurrentUser()
                    }
                )
            },
            onDismiss = { showUserNameInputDialog = false },
            existingUserNames = allUsers.map { it.userName }
        )
    }
}

/**
 * 个人数据配置区域组件 - 完全按照web版本样式
 */
@Composable
private fun PersonalDataConfigSection(
    viewModel: MainViewModel,
    shouldAutoLoadUltimate: Boolean = false
) {
    val context = LocalContext.current
    val storage = remember { UltimateDataStorage(context) }
    val uiState by viewModel.uiState.collectAsState()
    val multiUserDataManager = remember { MultiUserDataManager(context) }
    
    // 状态管理
    var ultimateSkills by remember { mutableStateOf(UltimateSkillsState()) }
    var recipeLimits by remember { mutableStateOf(RecipeLimitsState()) }
    var recipePrices by remember { mutableStateOf(RecipePricesState()) }
    var currentUserId by remember { mutableStateOf(multiUserDataManager.getCurrentUserId()) }
    
    // 监听用户切换，当用户ID改变时重新加载数据
    LaunchedEffect(Unit) {
        while (true) {
            val newUserId = multiUserDataManager.getCurrentUserId()
            if (newUserId != currentUserId) {
                currentUserId = newUserId
                // 用户切换时清空当前数据，重新从存储加载
                if (newUserId != null) {
                    storage.loadUltimateData()?.let { (skills, limits, prices) ->
                        ultimateSkills = skills
                        recipeLimits = limits
                        recipePrices = prices
                    } ?: run {
                        // 如果新用户没有保存的数据，重置为初始状态
                        ultimateSkills = UltimateSkillsState()
                        recipeLimits = RecipeLimitsState()
                        recipePrices = RecipePricesState()
                    }
                }
            }
            delay(1000) // 每秒检查一次用户切换
        }
    }
    
    // 应用启动时自动加载上次保存的数据
    LaunchedEffect(currentUserId) {
        if (currentUserId != null) {
            storage.loadUltimateData()?.let { (skills, limits, prices) ->
                ultimateSkills = skills
                recipeLimits = limits
                recipePrices = prices
            }
        }
    }
    
    // 跟踪验证状态变化，在导入成功时自动触发读取已修炼
    var previousValidatingState by remember { mutableStateOf(uiState.isValidating) }
    var hasTriggeredAutoLoad by remember { mutableStateOf(false) }
    
    LaunchedEffect(uiState.isValidating, uiState.isCodeValid) {
        // 当验证状态从true变为false，且导入成功时，自动触发读取已修炼
        if (previousValidatingState && !uiState.isValidating && uiState.isCodeValid && !hasTriggeredAutoLoad) {
            // 延迟一小段时间确保数据已完全加载
            delay(500)
            
            // 自动触发读取已修炼逻辑
                loadUltimateSkills(viewModel) { skills, limits, prices ->
                    ultimateSkills = skills
                    recipeLimits = limits
                    recipePrices = prices
                    // 保存数据到本地存储
                    storage.saveUltimateData(skills, limits, prices)
                }
            
            // 标记已触发过自动加载，避免重复触发
            hasTriggeredAutoLoad = true
            }
        
        // 当开始新的验证时，重置自动加载标记
        if (uiState.isValidating && !previousValidatingState) {
            hasTriggeredAutoLoad = false
        }
        
        // 更新之前的验证状态
        previousValidatingState = uiState.isValidating
    }
    
    // 监听外部触发的自动读取已修炼
    LaunchedEffect(shouldAutoLoadUltimate) {
        if (shouldAutoLoadUltimate) {
            // 延迟一段时间确保数据已完全加载
            delay(500)
            
            // 自动触发读取已修炼逻辑
            loadUltimateSkills(viewModel) { skills, limits, prices ->
                ultimateSkills = skills
                recipeLimits = limits
                recipePrices = prices
                // 保存数据到本地存储
                storage.saveUltimateData(skills, limits, prices)
            }
        }
    }
    
    Card(
        colors = getChefBoxCompatibleCardColors()
    ) {
        Column(
            modifier = Modifier.padding(12.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            Text(
                text = "修炼数据",
                fontSize = 16.sp,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.primary
            )

            // 修炼技法配置
            UltimateSkillsSection(
                ultimateSkills = ultimateSkills,
                onSkillsChange = { newSkills ->
                    ultimateSkills = newSkills
                    // 保存到本地存储
                    storage.saveUltimateData(ultimateSkills, recipeLimits, recipePrices)
                }
            )

            // 菜谱上限配置
            RecipeLimitsSection(
                recipeLimits = recipeLimits,
                onLimitsChange = { newLimits ->
                    recipeLimits = newLimits
                    // 保存到本地存储
                    storage.saveUltimateData(ultimateSkills, recipeLimits, recipePrices)
                }
            )

            // 菜谱售价配置
            RecipePricesSection(
                recipePrices = recipePrices,
                onPricesChange = { newPrices ->
                    recipePrices = newPrices
                    // 保存到本地存储
                    storage.saveUltimateData(ultimateSkills, recipeLimits, recipePrices)
                }
            )

            // 下拉选择和按钮区域
            DropdownAndButtonsSection(
                viewModel = viewModel,
                onLoadUltimate = { skills, limits, prices ->
                    ultimateSkills = skills
                    recipeLimits = limits
                    recipePrices = prices
                    // 保存数据到本地存储
                    storage.saveUltimateData(skills, limits, prices)
                }
            )
            

        }
    }
}

/**
 * 修炼技法配置区域 - 紧凑布局
 */
@Composable
private fun UltimateSkillsSection(
    ultimateSkills: UltimateSkillsState = UltimateSkillsState(),
    onSkillsChange: (UltimateSkillsState) -> Unit = {}
) {
    var stirfryValue by remember { mutableStateOf(ultimateSkills.stirfry.toString()) }
    var boilValue by remember { mutableStateOf(ultimateSkills.boil.toString()) }
    var knifeValue by remember { mutableStateOf(ultimateSkills.knife.toString()) }
    var fryValue by remember { mutableStateOf(ultimateSkills.fry.toString()) }
    var bakeValue by remember { mutableStateOf(ultimateSkills.bake.toString()) }
    var steamValue by remember { mutableStateOf(ultimateSkills.steam.toString()) }
    var maleSkillValue by remember { mutableStateOf(ultimateSkills.maleAllSkill.toString()) }
    var femaleSkillValue by remember { mutableStateOf(ultimateSkills.femaleAllSkill.toString()) }

    // 当外部状态更新时，更新内部状态
    LaunchedEffect(ultimateSkills) {
        stirfryValue = if (ultimateSkills.stirfry > 0) ultimateSkills.stirfry.toString() else ""
        boilValue = if (ultimateSkills.boil > 0) ultimateSkills.boil.toString() else ""
        knifeValue = if (ultimateSkills.knife > 0) ultimateSkills.knife.toString() else ""
        fryValue = if (ultimateSkills.fry > 0) ultimateSkills.fry.toString() else ""
        bakeValue = if (ultimateSkills.bake > 0) ultimateSkills.bake.toString() else ""
        steamValue = if (ultimateSkills.steam > 0) ultimateSkills.steam.toString() else ""
        maleSkillValue = if (ultimateSkills.maleAllSkill > 0) ultimateSkills.maleAllSkill.toString() else ""
        femaleSkillValue = if (ultimateSkills.femaleAllSkill > 0) ultimateSkills.femaleAllSkill.toString() else ""
    }

    // 辅助函数：更新技法状态
    fun updateSkills() {
        val newSkills = UltimateSkillsState(
            stirfry = stirfryValue.toIntOrNull() ?: 0,
            boil = boilValue.toIntOrNull() ?: 0,
            knife = knifeValue.toIntOrNull() ?: 0,
            fry = fryValue.toIntOrNull() ?: 0,
            bake = bakeValue.toIntOrNull() ?: 0,
            steam = steamValue.toIntOrNull() ?: 0,
            maleAllSkill = maleSkillValue.toIntOrNull() ?: 0,
            femaleAllSkill = femaleSkillValue.toIntOrNull() ?: 0
        )
        onSkillsChange(newSkills)
    }

    Column {
        Text(
            text = "技法加成",
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.primary
        )

        Spacer(modifier = Modifier.height(6.dp))

        // 第一行：前三个技法
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            SkillInputField(
                label = "炒",
                value = stirfryValue,
                onValueChange = {
                    stirfryValue = it
                    updateSkills()
                }
            )
            SkillInputField(
                label = "煮",
                value = boilValue,
                onValueChange = {
                    boilValue = it
                    updateSkills()
                }
            )
            SkillInputField(
                label = "切",
                value = knifeValue,
                onValueChange = {
                    knifeValue = it
                    updateSkills()
                }
            )
        }

        Spacer(modifier = Modifier.height(6.dp))

        // 第二行：后三个技法
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            SkillInputField(
                label = "炸",
                value = fryValue,
                onValueChange = {
                    fryValue = it
                    updateSkills()
                }
            )
            SkillInputField(
                label = "烤",
                value = bakeValue,
                onValueChange = {
                    bakeValue = it
                    updateSkills()
                }
            )
            SkillInputField(
                label = "蒸",
                value = steamValue,
                onValueChange = {
                    steamValue = it
                    updateSkills()
                }
            )
        }

        Spacer(modifier = Modifier.height(6.dp))

        // 第二行：性别技法
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            SkillInputField(
                label = "男厨全技法",
                value = maleSkillValue,
                onValueChange = {
                    maleSkillValue = it
                    updateSkills()
                }
            )
            SkillInputField(
                label = "女厨全技法",
                value = femaleSkillValue,
                onValueChange = {
                    femaleSkillValue = it
                    updateSkills()
                }
            )
        }
    }
}

/**
 * 菜谱上限配置区域 - 紧凑布局
 */
@Composable
private fun RecipeLimitsSection(
    recipeLimits: RecipeLimitsState = RecipeLimitsState(),
    onLimitsChange: (RecipeLimitsState) -> Unit = {}
) {
    var star1Limit by remember { mutableStateOf(recipeLimits.star1.toString()) }
    var star2Limit by remember { mutableStateOf(recipeLimits.star2.toString()) }
    var star3Limit by remember { mutableStateOf(recipeLimits.star3.toString()) }
    var star4Limit by remember { mutableStateOf(recipeLimits.star4.toString()) }
    var star5Limit by remember { mutableStateOf(recipeLimits.star5.toString()) }

    // 当外部状态更新时，更新内部状态
    LaunchedEffect(recipeLimits) {
        star1Limit = if (recipeLimits.star1 > 0) recipeLimits.star1.toString() else ""
        star2Limit = if (recipeLimits.star2 > 0) recipeLimits.star2.toString() else ""
        star3Limit = if (recipeLimits.star3 > 0) recipeLimits.star3.toString() else ""
        star4Limit = if (recipeLimits.star4 > 0) recipeLimits.star4.toString() else ""
        star5Limit = if (recipeLimits.star5 > 0) recipeLimits.star5.toString() else ""
    }

    // 辅助函数：更新菜谱上限状态
    fun updateLimits() {
        val newLimits = RecipeLimitsState(
            star1 = star1Limit.toIntOrNull() ?: 0,
            star2 = star2Limit.toIntOrNull() ?: 0,
            star3 = star3Limit.toIntOrNull() ?: 0,
            star4 = star4Limit.toIntOrNull() ?: 0,
            star5 = star5Limit.toIntOrNull() ?: 0
        )
        onLimitsChange(newLimits)
    }

    Column {
        Text(
            text = "菜谱上限",
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.primary
        )

        Spacer(modifier = Modifier.height(6.dp))

        // 第一行：1-3星
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            SkillInputField(
                label = "1星",
                value = star1Limit,
                onValueChange = {
                    star1Limit = it
                    updateLimits()
                }
            )
            SkillInputField(
                label = "2星",
                value = star2Limit,
                onValueChange = {
                    star2Limit = it
                    updateLimits()
                }
            )
            SkillInputField(
                label = "3星",
                value = star3Limit,
                onValueChange = {
                    star3Limit = it
                    updateLimits()
                }
            )
        }

        Spacer(modifier = Modifier.height(6.dp))

        // 第二行：4-5星
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            SkillInputField(
                label = "4星",
                value = star4Limit,
                onValueChange = {
                    star4Limit = it
                    updateLimits()
                }
            )
            SkillInputField(
                label = "5星",
                value = star5Limit,
                onValueChange = {
                    star5Limit = it
                    updateLimits()
                }
            )
        }
    }
}

/**
 * 菜谱售价配置区域 - 紧凑布局
 */
@Composable
private fun RecipePricesSection(
    recipePrices: RecipePricesState = RecipePricesState(),
    onPricesChange: (RecipePricesState) -> Unit = {}
) {
    var star1Price by remember { mutableStateOf(recipePrices.star1.toString()) }
    var star2Price by remember { mutableStateOf(recipePrices.star2.toString()) }
    var star3Price by remember { mutableStateOf(recipePrices.star3.toString()) }
    var star4Price by remember { mutableStateOf(recipePrices.star4.toString()) }
    var star5Price by remember { mutableStateOf(recipePrices.star5.toString()) }

    // 当外部状态更新时，更新内部状态
    LaunchedEffect(recipePrices) {
        star1Price = if (recipePrices.star1 > 0) recipePrices.star1.toString() else ""
        star2Price = if (recipePrices.star2 > 0) recipePrices.star2.toString() else ""
        star3Price = if (recipePrices.star3 > 0) recipePrices.star3.toString() else ""
        star4Price = if (recipePrices.star4 > 0) recipePrices.star4.toString() else ""
        star5Price = if (recipePrices.star5 > 0) recipePrices.star5.toString() else ""
    }

    // 辅助函数：更新菜谱售价状态
    fun updatePrices() {
        val newPrices = RecipePricesState(
            star1 = star1Price.toIntOrNull() ?: 0,
            star2 = star2Price.toIntOrNull() ?: 0,
            star3 = star3Price.toIntOrNull() ?: 0,
            star4 = star4Price.toIntOrNull() ?: 0,
            star5 = star5Price.toIntOrNull() ?: 0
        )
        onPricesChange(newPrices)
    }

    Column {
        Text(
            text = "菜谱售价",
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.primary
        )

        Spacer(modifier = Modifier.height(6.dp))

        // 第一行：1-3星
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            SkillInputField(
                label = "1星",
                value = star1Price,
                onValueChange = {
                    star1Price = it
                    updatePrices()
                },
                suffix = "%"
            )
            SkillInputField(
                label = "2星",
                value = star2Price,
                onValueChange = {
                    star2Price = it
                    updatePrices()
                },
                suffix = "%"
            )
            SkillInputField(
                label = "3星",
                value = star3Price,
                onValueChange = {
                    star3Price = it
                    updatePrices()
                },
                suffix = "%"
            )
        }

        Spacer(modifier = Modifier.height(6.dp))

        // 第二行：4-5星
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            SkillInputField(
                label = "4星",
                value = star4Price,
                onValueChange = {
                    star4Price = it
                    updatePrices()
                },
                suffix = "%"
            )
            SkillInputField(
                label = "5星",
                value = star5Price,
                onValueChange = {
                    star5Price = it
                    updatePrices()
                },
                suffix = "%"
            )
        }
    }
}

/**
 * 技能输入字段组件 - 紧凑样式，适合三位数输入
 */
@Composable
private fun SkillInputField(
    label: String,
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    suffix: String = ""
) {
    Row(
        modifier = modifier,
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        Text(
            text = label,
            fontSize = 13.sp,
            color = MaterialTheme.colorScheme.onSurface
        )

        Box(
            modifier = Modifier
                .width(50.dp)
                .height(24.dp)
                .border(
                    1.dp,
                    MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
                    RoundedCornerShape(4.dp)
                ),
            contentAlignment = Alignment.Center
        ) {
            BasicTextField(
                value = value,
                onValueChange = onValueChange,
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight(),
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                singleLine = true,
                textStyle = TextStyle(
                    fontSize = 12.sp,
                    textAlign = TextAlign.Center,
                    color = MaterialTheme.colorScheme.onSurface,
                    lineHeight = 12.sp
                ),
                decorationBox = { innerTextField ->
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        innerTextField()
                    }
                }
            )
        }

        if (suffix.isNotEmpty()) {
            Text(
                text = suffix,
                fontSize = 13.sp,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

/**
 * 按钮区域 - 修复按钮布局
 */
@Composable
private fun DropdownAndButtonsSection(
    viewModel: MainViewModel,
    onLoadUltimate: (UltimateSkillsState, RecipeLimitsState, RecipePricesState) -> Unit
) {
    val context = LocalContext.current
    // 按钮区域 - 分两行显示
    Column(
        verticalArrangement = Arrangement.spacedBy(6.dp)
    ) {
        // 第一行按钮
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
                                        Button(
                            onClick = {
                                // 确保加载当前用户的最新数据
                                val context = viewModel.getApplication<Application>()
                                val multiUserDataManager = MultiUserDataManager(context)
                                val currentUser = multiUserDataManager.getCurrentUser()
                                val currentUserData = currentUser?.let { multiUserDataManager.getUserData(it) }
                                
                                if (currentUserData != null) {
                                    // 重新加载当前用户数据到ViewModel
                                    viewModel.switchToUser(currentUserData, multiUserDataManager) {
                                        // 数据加载完成后执行读取已修炼
                                        loadUltimateSkills(viewModel, onLoadUltimate)
                                    }
                                } else {
                                    // 如果没有当前用户，直接执行读取已修炼
                                    loadUltimateSkills(viewModel, onLoadUltimate)
                                }
                            },
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.primary
            ),
            modifier = Modifier
                .weight(1f)
                .height(32.dp),
            contentPadding = PaddingValues(0.dp)
        ) {
            Text(
                text = "读取已修炼",
                fontSize = 11.sp,
                textAlign = TextAlign.Center
            )
        }

            Button(
                onClick = {
                    loadOwnedUltimateSkills(viewModel, onLoadUltimate)
                },
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.tertiary
                ),
                modifier = Modifier
                    .weight(1f)
                    .height(32.dp),
                contentPadding = PaddingValues(0.dp)
            ) {
                Text(
                    text = "读取已有全修炼",
                    fontSize = 10.sp,
                    textAlign = TextAlign.Center
                )
            }
        }

        // 第二行按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
        Button(
            onClick = { 
                loadAllUltimateSkills(viewModel, onLoadUltimate)
            },
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.secondary
            ),
            modifier = Modifier
                .weight(1f)
                .height(32.dp),
            contentPadding = PaddingValues(0.dp)
        ) {
            Text(
                text = "读取全修炼",
                fontSize = 11.sp,
                textAlign = TextAlign.Center
            )
        }

        Button(
            onClick = { 
                clearUltimateSkills(context, onLoadUltimate)
            },
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.error
            ),
            modifier = Modifier
                .weight(1f)
                .height(32.dp),
            contentPadding = PaddingValues(0.dp)
        ) {
            Text(
                text = "清空修炼",
                fontSize = 11.sp,
                textAlign = TextAlign.Center
            )
            }
        }
    }
}

/**
 * 修炼技法状态数据类
 */
data class UltimateSkillsState(
    val stirfry: Int = 0,
    val boil: Int = 0,
    val knife: Int = 0,
    val fry: Int = 0,
    val bake: Int = 0,
    val steam: Int = 0,
    val maleAllSkill: Int = 0,
    val femaleAllSkill: Int = 0
)

/**
 * 菜谱上限状态数据类
 */
data class RecipeLimitsState(
    val star1: Int = 0,
    val star2: Int = 0,
    val star3: Int = 0,
    val star4: Int = 0,
    val star5: Int = 0
)

/**
 * 菜谱售价状态数据类
 */
data class RecipePricesState(
    val star1: Int = 0,
    val star2: Int = 0,
    val star3: Int = 0,
    val star4: Int = 0,
    val star5: Int = 0
)

/**
 * 读取已修炼按钮逻辑 - 只处理已修炼的厨师
 */
private fun loadUltimateSkills(
    viewModel: MainViewModel, 
    onLoadUltimate: (UltimateSkillsState, RecipeLimitsState, RecipePricesState) -> Unit
) {
    // 强制刷新，确保获取最新的游戏数据
    val gameData = viewModel.gameData.value ?: return
    
    // 调试信息：检查当前用户
    val context = viewModel.getApplication<Application>()
    val multiUserDataManager = MultiUserDataManager(context)
    val currentUser = multiUserDataManager.getCurrentUser()

    // 初始化累计值
    var totalStirfry = 0
    var totalBoil = 0
    var totalKnife = 0
    var totalFry = 0
    var totalBake = 0
    var totalSteam = 0
    var totalMaleAllSkill = 0
    var totalFemaleAllSkill = 0

    var totalStar1Limit = 0
    var totalStar2Limit = 0
    var totalStar3Limit = 0
    var totalStar4Limit = 0
    var totalStar5Limit = 0

    var totalStar1Price = 0
    var totalStar2Price = 0
    var totalStar3Price = 0
    var totalStar4Price = 0
    var totalStar5Price = 0

    // 遍历所有已修炼的厨师
    var ultCount = 0
    for (chef in gameData.chefs) {
        if (!chef.ult) continue // 只处理已修炼的厨师

        ultCount++

        val skillsList = chef.getAllUltimateSkills()
        for (ultimateSkillId in skillsList) {
            // 跳过上场类技能，只处理个人类技能
            if (!isPartialSkill(ultimateSkillId)) {
                // 个人类技能，每个厨师都累计
                when (ultimateSkillId) {
                    // 全体厨师技法加成 (330-353) - 个人类技能，每个厨师都累计
                    330, 336, 342, 348 -> totalStirfry += getSkillValue(ultimateSkillId) // 炒技法
                    331, 337, 343, 349 -> totalBake += getSkillValue(ultimateSkillId)   // 烤技法
                    332, 338, 344, 350 -> totalSteam += getSkillValue(ultimateSkillId)  // 蒸技法
                    333, 339, 345, 351 -> totalBoil += getSkillValue(ultimateSkillId)   // 煮技法
                    334, 340, 346, 352 -> totalFry += getSkillValue(ultimateSkillId)    // 炸技法
                    335, 341, 347, 353 -> totalKnife += getSkillValue(ultimateSkillId)  // 切技法

                    // 全体男厨师全技法+1 (366)
                    366 -> totalMaleAllSkill += 1

                    // 全体男厨师全技法+3 (678)
                    678 -> totalMaleAllSkill += 3

                    // 全体厨师全技法+1 (367, 491)
                    367, 491 -> {
                        totalStirfry += 1
                        totalBoil += 1
                        totalKnife += 1
                        totalFry += 1
                        totalBake += 1
                        totalSteam += 1
                    }

                    // 全体女厨师全技法+1 (431) - 只加到女厨字段
                    431 -> totalFemaleAllSkill += 1

                    // 全体厨师全技法+2 (432)
                    432 -> {
                        totalStirfry += 2
                        totalBoil += 2
                        totalKnife += 2
                        totalFry += 2
                        totalBake += 2
                        totalSteam += 2
                    }

                    // 全体厨师全技法+3 (433)
                    433 -> {
                        totalStirfry += 3
                        totalBoil += 3
                        totalKnife += 3
                        totalFry += 3
                        totalBake += 3
                        totalSteam += 3
                    }

                    // 全体女厨师全技法+3 (679)
                    679 -> totalFemaleAllSkill += 3

                    // 全体女厨师全技法+2 (775) - 只加到女厨字段
                    775 -> totalFemaleAllSkill += 2

                    // 菜谱上限加成 (320-329)
                    320, 325 -> totalStar1Limit += getSkillValue(ultimateSkillId) // 1星菜谱上限
                    321 -> totalStar2Limit += 1  // 2星菜谱上限+1
                    322 -> totalStar3Limit += 1  // 3星菜谱上限+1
                    323 -> totalStar4Limit += 1  // 4星菜谱上限+1
                    324 -> totalStar5Limit += 1  // 5星菜谱上限+1

                    // 额外的菜谱上限技能
                    749 -> totalStar1Limit += 3  // 1星菜谱上限+3

                    // 菜谱上限技能
                    354, 360 -> totalStar1Limit += getSkillValue(ultimateSkillId) // 1星菜谱上限
                    355, 361 -> totalStar2Limit += getSkillValue(ultimateSkillId) // 2星菜谱上限
                    356, 362 -> totalStar3Limit += getSkillValue(ultimateSkillId) // 3星菜谱上限
                    357, 363 -> totalStar4Limit += getSkillValue(ultimateSkillId) // 4星菜谱上限
                    358, 364 -> totalStar5Limit += getSkillValue(ultimateSkillId) // 5星菜谱上限

                    // 菜谱售价加成 (310-319)
                    310, 315 -> totalStar1Price += getSkillValue(ultimateSkillId) // 1星菜谱售价
                    311 -> totalStar2Price += 1  // 2星菜谱售价+1%
                    312, 317 -> totalStar3Price += getSkillValue(ultimateSkillId) // 3星菜谱售价
                    313, 318 -> totalStar4Price += getSkillValue(ultimateSkillId) // 4星菜谱售价
                    314, 319 -> totalStar5Price += getSkillValue(ultimateSkillId) // 5星菜谱售价

                    // 额外的菜谱售价技能
                    534 -> totalStar2Price += 10  // 2星菜谱售价+10%
                    535 -> totalStar3Price += 6   // 3星菜谱售价+6%
                    579 -> totalStar5Price += 3   // 5星菜谱售价+3%
                    584 -> totalStar3Price += 2   // 3星菜谱售价+2%
                    692 -> totalStar4Price += 2   // 4星菜谱售价+2%
                    697 -> totalStar2Price += 3   // 2星菜谱售价+3%
                    1015 -> totalStar1Price += 2  // 1星菜谱售价+2%
                    1018 -> {                     // 1星和2星菜谱售价各+3%
                        totalStar1Price += 3
                        totalStar2Price += 3
                    }

                    // 默认分支 - 处理未知技能
                    else -> {
                        // 尝试通过技能数据自动处理
                        processUnknownSkill(ultimateSkillId, gameData) { skillType: String, value: Int ->
                            when (skillType) {
                                "stirfry" -> totalStirfry += value
                                "boil" -> totalBoil += value
                                "knife" -> totalKnife += value
                                "fry" -> totalFry += value
                                "bake" -> totalBake += value
                                "steam" -> totalSteam += value
                                "maleAllSkill" -> totalMaleAllSkill += value
                                "femaleAllSkill" -> totalFemaleAllSkill += value
                                "star1Limit" -> totalStar1Limit += value
                                "star2Limit" -> totalStar2Limit += value
                                "star3Limit" -> totalStar3Limit += value
                                "star4Limit" -> totalStar4Limit += value
                                "star5Limit" -> totalStar5Limit += value
                                "star1Price" -> totalStar1Price += value
                                "star2Price" -> totalStar2Price += value
                                "star3Price" -> totalStar3Price += value
                                "star4Price" -> totalStar4Price += value
                                "star5Price" -> totalStar5Price += value
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 更新UI状态
    val ultimateSkills = UltimateSkillsState(
        stirfry = totalStirfry,
        boil = totalBoil,
        knife = totalKnife,
        fry = totalFry,
        bake = totalBake,
        steam = totalSteam,
        maleAllSkill = totalMaleAllSkill,
        femaleAllSkill = totalFemaleAllSkill
    )
    
    val recipeLimits = RecipeLimitsState(
        star1 = totalStar1Limit,
        star2 = totalStar2Limit,
        star3 = totalStar3Limit,
        star4 = totalStar4Limit,
        star5 = totalStar5Limit
    )
    
    val recipePrices = RecipePricesState(
        star1 = totalStar1Price,
        star2 = totalStar2Price,
        star3 = totalStar3Price,
        star4 = totalStar4Price,
        star5 = totalStar5Price
    )
    
    // 识别并保存当前用户的光环厨师
    val appContext = viewModel.getApplication<Application>()
    val personalDataManager = PersonalDataManager(appContext)
    val allAuraChefs = gameData.chefs.filter { chef ->
        isAuraChef(chef, gameData.skills)
    }
    
    // 自动选择已拥有且已修炼的光环厨师并保存
    val ownedAndUltimateAuraChefs = allAuraChefs.filter { chef ->
        chef.got && chef.ult
    }.map { it.name }.toSet()
    
    if (ownedAndUltimateAuraChefs.isNotEmpty()) {
        personalDataManager.saveUserAuraChefs(ownedAndUltimateAuraChefs)
        println("DEBUG: 为当前用户保存光环厨师: ${ownedAndUltimateAuraChefs.size} 个")
    }
    
    onLoadUltimate(ultimateSkills, recipeLimits, recipePrices)
}

/**
 * 读取已有全修炼按钮逻辑 - 模拟所有已拥有厨师都已修炼的情况
 */
private fun loadOwnedUltimateSkills(
    viewModel: MainViewModel,
    onLoadUltimate: (UltimateSkillsState, RecipeLimitsState, RecipePricesState) -> Unit
) {
    val gameData = viewModel.gameData.value ?: return

    // 初始化累计值
    var totalStirfry = 0
    var totalBoil = 0
    var totalKnife = 0
    var totalFry = 0
    var totalBake = 0
    var totalSteam = 0
    var totalMaleAllSkill = 0
    var totalFemaleAllSkill = 0

    var totalStar1Limit = 0
    var totalStar2Limit = 0
    var totalStar3Limit = 0
    var totalStar4Limit = 0
    var totalStar5Limit = 0

    var totalStar1Price = 0
    var totalStar2Price = 0
    var totalStar3Price = 0
    var totalStar4Price = 0
    var totalStar5Price = 0

    // 遍历所有已拥有的厨师，假设都已修炼
    var ultCount = 0
    for (chef in gameData.chefs) {
        if (!chef.got) continue // 只处理已拥有的厨师（不管是否已修炼）

        ultCount++

        val skillsList = chef.getAllUltimateSkills()
        for (ultimateSkillId in skillsList) {
            // 跳过上场类技能，只处理个人类技能
            if (!isPartialSkill(ultimateSkillId)) {
                // 个人类技能，每个厨师都累计
                when (ultimateSkillId) {
                    // 全体厨师技法加成 (330-353) - 个人类技能，每个厨师都累计
                    330, 336, 342, 348 -> totalStirfry += getSkillValue(ultimateSkillId) // 炒技法
                    331, 337, 343, 349 -> totalBake += getSkillValue(ultimateSkillId)   // 烤技法
                    332, 338, 344, 350 -> totalSteam += getSkillValue(ultimateSkillId)  // 蒸技法
                    333, 339, 345, 351 -> totalBoil += getSkillValue(ultimateSkillId)   // 煮技法
                    334, 340, 346, 352 -> totalFry += getSkillValue(ultimateSkillId)    // 炸技法
                    335, 341, 347, 353 -> totalKnife += getSkillValue(ultimateSkillId)  // 切技法

                    // 全体男厨师全技法+1 (366)
                    366 -> totalMaleAllSkill += 1

                    // 全体男厨师全技法+3 (678)
                    678 -> totalMaleAllSkill += 3

                    // 全体厨师全技法+1 (367, 491)
                    367, 491 -> {
                        totalStirfry += 1
                        totalBoil += 1
                        totalKnife += 1
                        totalFry += 1
                        totalBake += 1
                        totalSteam += 1
                    }

                    // 全体女厨师全技法+1 (431) - 只加到女厨字段
                    431 -> totalFemaleAllSkill += 1

                    // 全体厨师全技法+2 (432)
                    432 -> {
                        totalStirfry += 2
                        totalBoil += 2
                        totalKnife += 2
                        totalFry += 2
                        totalBake += 2
                        totalSteam += 2
                    }

                    // 全体厨师全技法+3 (433)
                    433 -> {
                        totalStirfry += 3
                        totalBoil += 3
                        totalKnife += 3
                        totalFry += 3
                        totalBake += 3
                        totalSteam += 3
                    }

                    // 全体女厨师全技法+3 (679)
                    679 -> totalFemaleAllSkill += 3

                    // 全体女厨师全技法+2 (775) - 只加到女厨字段
                    775 -> totalFemaleAllSkill += 2

                    // 菜谱上限加成 (320-329)
                    320, 325 -> totalStar1Limit += getSkillValue(ultimateSkillId) // 1星菜谱上限
                    321 -> totalStar2Limit += 1  // 2星菜谱上限+1
                    322 -> totalStar3Limit += 1  // 3星菜谱上限+1
                    323 -> totalStar4Limit += 1  // 4星菜谱上限+1
                    324 -> totalStar5Limit += 1  // 5星菜谱上限+1

                    // 额外的菜谱上限技能
                    749 -> totalStar1Limit += 3  // 1星菜谱上限+3

                    // 菜谱上限技能
                    354, 360 -> totalStar1Limit += getSkillValue(ultimateSkillId) // 1星菜谱上限
                    355, 361 -> totalStar2Limit += getSkillValue(ultimateSkillId) // 2星菜谱上限
                    356, 362 -> totalStar3Limit += getSkillValue(ultimateSkillId) // 3星菜谱上限
                    357, 363 -> totalStar4Limit += getSkillValue(ultimateSkillId) // 4星菜谱上限
                    358, 364 -> totalStar5Limit += getSkillValue(ultimateSkillId) // 5星菜谱上限

                    // 菜谱售价加成 (310-319)
                    310, 315 -> totalStar1Price += getSkillValue(ultimateSkillId) // 1星菜谱售价
                    311 -> totalStar2Price += 1  // 2星菜谱售价+1%
                    312, 317 -> totalStar3Price += getSkillValue(ultimateSkillId) // 3星菜谱售价
                    313, 318 -> totalStar4Price += getSkillValue(ultimateSkillId) // 4星菜谱售价
                    314, 319 -> totalStar5Price += getSkillValue(ultimateSkillId) // 5星菜谱售价

                    // 额外的菜谱售价技能
                    534 -> totalStar2Price += 10  // 2星菜谱售价+10%
                    535 -> totalStar3Price += 6   // 3星菜谱售价+6%
                    579 -> totalStar5Price += 3   // 5星菜谱售价+3%
                    584 -> totalStar3Price += 2   // 3星菜谱售价+2%
                    692 -> totalStar4Price += 2   // 4星菜谱售价+2%
                    697 -> totalStar2Price += 3   // 2星菜谱售价+3%
                    1015 -> totalStar1Price += 2  // 1星菜谱售价+2%
                    1018 -> {                     // 1星和2星菜谱售价各+3%
                        totalStar1Price += 3
                        totalStar2Price += 3
                    }

                    // 默认分支 - 处理未知技能
                    else -> {
                        // 尝试通过技能数据自动处理
                        processUnknownSkill(ultimateSkillId, gameData) { skillType: String, value: Int ->
                            when (skillType) {
                                "stirfry" -> totalStirfry += value
                                "boil" -> totalBoil += value
                                "knife" -> totalKnife += value
                                "fry" -> totalFry += value
                                "bake" -> totalBake += value
                                "steam" -> totalSteam += value
                                "maleAllSkill" -> totalMaleAllSkill += value
                                "femaleAllSkill" -> totalFemaleAllSkill += value
                                "star1Limit" -> totalStar1Limit += value
                                "star2Limit" -> totalStar2Limit += value
                                "star3Limit" -> totalStar3Limit += value
                                "star4Limit" -> totalStar4Limit += value
                                "star5Limit" -> totalStar5Limit += value
                                "star1Price" -> totalStar1Price += value
                                "star2Price" -> totalStar2Price += value
                                "star3Price" -> totalStar3Price += value
                                "star4Price" -> totalStar4Price += value
                                "star5Price" -> totalStar5Price += value
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 更新UI状态
    val ultimateSkills = UltimateSkillsState(
        stirfry = totalStirfry,
        boil = totalBoil,
        knife = totalKnife,
        fry = totalFry,
        bake = totalBake,
        steam = totalSteam,
        maleAllSkill = totalMaleAllSkill,
        femaleAllSkill = totalFemaleAllSkill
    )
    
    val recipeLimits = RecipeLimitsState(
        star1 = totalStar1Limit,
        star2 = totalStar2Limit,
        star3 = totalStar3Limit,
        star4 = totalStar4Limit,
        star5 = totalStar5Limit
    )
    
    val recipePrices = RecipePricesState(
        star1 = totalStar1Price,
        star2 = totalStar2Price,
        star3 = totalStar3Price,
        star4 = totalStar4Price,
        star5 = totalStar5Price
    )
    
    onLoadUltimate(ultimateSkills, recipeLimits, recipePrices)
}

/**
 * 读取全修炼按钮逻辑 - 模拟所有厨师都已修炼的情况
 */
private fun loadAllUltimateSkills(
    viewModel: MainViewModel,
    onLoadUltimate: (UltimateSkillsState, RecipeLimitsState, RecipePricesState) -> Unit
) {
    val gameData = viewModel.gameData.value ?: return
    
    // 初始化累计值
    var totalStirfry = 0
    var totalBoil = 0
    var totalKnife = 0
    var totalFry = 0
    var totalBake = 0
    var totalSteam = 0
    var totalMaleAllSkill = 0
    var totalFemaleAllSkill = 0

    var totalStar1Limit = 0
    var totalStar2Limit = 0
    var totalStar3Limit = 0
    var totalStar4Limit = 0
    var totalStar5Limit = 0

    var totalStar1Price = 0
    var totalStar2Price = 0
    var totalStar3Price = 0
    var totalStar4Price = 0
    var totalStar5Price = 0

    // 遍历所有厨师，假设都已修炼
    var ultCount = 0
    for (chef in gameData.chefs) {
        ultCount++

        val skillsList = chef.getAllUltimateSkills()
        for (ultimateSkillId in skillsList) {
            // 跳过上场类技能，只处理个人类技能
            if (!isPartialSkill(ultimateSkillId)) {
                // 个人类技能，每个厨师都累计
                when (ultimateSkillId) {
                    // 全体厨师技法加成 (330-353) - 个人类技能，每个厨师都累计
                    330, 336, 342, 348 -> totalStirfry += getSkillValue(ultimateSkillId) // 炒技法
                    331, 337, 343, 349 -> totalBake += getSkillValue(ultimateSkillId)   // 烤技法
                    332, 338, 344, 350 -> totalSteam += getSkillValue(ultimateSkillId)  // 蒸技法
                    333, 339, 345, 351 -> totalBoil += getSkillValue(ultimateSkillId)   // 煮技法
                    334, 340, 346, 352 -> totalFry += getSkillValue(ultimateSkillId)    // 炸技法
                    335, 341, 347, 353 -> totalKnife += getSkillValue(ultimateSkillId)  // 切技法

                    // 全体男厨师全技法+1 (366)
                    366 -> totalMaleAllSkill += 1

                    // 全体男厨师全技法+3 (678)
                    678 -> totalMaleAllSkill += 3

                    // 全体厨师全技法+1 (367, 491)
                    367, 491 -> {
                        totalStirfry += 1
                        totalBoil += 1
                        totalKnife += 1
                        totalFry += 1
                        totalBake += 1
                        totalSteam += 1
                    }

                    // 全体女厨师全技法+1 (431) - 只加到女厨字段
                    431 -> totalFemaleAllSkill += 1

                    // 全体厨师全技法+2 (432)
                    432 -> {
                        totalStirfry += 2
                        totalBoil += 2
                        totalKnife += 2
                        totalFry += 2
                        totalBake += 2
                        totalSteam += 2
                    }

                    // 全体厨师全技法+3 (433)
                    433 -> {
                        totalStirfry += 3
                        totalBoil += 3
                        totalKnife += 3
                        totalFry += 3
                        totalBake += 3
                        totalSteam += 3
                    }

                    // 全体女厨师全技法+3 (679)
                    679 -> totalFemaleAllSkill += 3

                    // 全体女厨师全技法+2 (775) - 只加到女厨字段
                    775 -> totalFemaleAllSkill += 2

                    // 菜谱上限加成 (320-329)
                    320, 325 -> totalStar1Limit += getSkillValue(ultimateSkillId) // 1星菜谱上限
                    321 -> totalStar2Limit += 1  // 2星菜谱上限+1
                    322 -> totalStar3Limit += 1  // 3星菜谱上限+1
                    323 -> totalStar4Limit += 1  // 4星菜谱上限+1
                    324 -> totalStar5Limit += 1  // 5星菜谱上限+1

                    // 额外的菜谱上限技能
                    749 -> totalStar1Limit += 3  // 1星菜谱上限+3

                    // 菜谱上限技能
                    354, 360 -> totalStar1Limit += getSkillValue(ultimateSkillId) // 1星菜谱上限
                    355, 361 -> totalStar2Limit += getSkillValue(ultimateSkillId) // 2星菜谱上限
                    356, 362 -> totalStar3Limit += getSkillValue(ultimateSkillId) // 3星菜谱上限
                    357, 363 -> totalStar4Limit += getSkillValue(ultimateSkillId) // 4星菜谱上限
                    358, 364 -> totalStar5Limit += getSkillValue(ultimateSkillId) // 5星菜谱上限

                    // 菜谱售价加成 (310-319)
                    310, 315 -> totalStar1Price += getSkillValue(ultimateSkillId) // 1星菜谱售价
                    311 -> totalStar2Price += 1  // 2星菜谱售价+1%
                    312, 317 -> totalStar3Price += getSkillValue(ultimateSkillId) // 3星菜谱售价
                    313, 318 -> totalStar4Price += getSkillValue(ultimateSkillId) // 4星菜谱售价
                    314, 319 -> totalStar5Price += getSkillValue(ultimateSkillId) // 5星菜谱售价

                    // 额外的菜谱售价技能
                    534 -> totalStar2Price += 10  // 2星菜谱售价+10%
                    535 -> totalStar3Price += 6   // 3星菜谱售价+6%
                    579 -> totalStar5Price += 3   // 5星菜谱售价+3%
                    584 -> totalStar3Price += 2   // 3星菜谱售价+2%
                    692 -> totalStar4Price += 2   // 4星菜谱售价+2%
                    697 -> totalStar2Price += 3   // 2星菜谱售价+3%
                    1015 -> totalStar1Price += 2  // 1星菜谱售价+2%
                    1018 -> {                     // 1星和2星菜谱售价各+3%
                        totalStar1Price += 3
                        totalStar2Price += 3
                    }

                    // 默认分支 - 处理未知技能
                    else -> {
                        // 尝试通过技能数据自动处理
                        processUnknownSkill(ultimateSkillId, gameData) { skillType: String, value: Int ->
                            when (skillType) {
                                "stirfry" -> totalStirfry += value
                                "boil" -> totalBoil += value
                                "knife" -> totalKnife += value
                                "fry" -> totalFry += value
                                "bake" -> totalBake += value
                                "steam" -> totalSteam += value
                                "maleAllSkill" -> totalMaleAllSkill += value
                                "femaleAllSkill" -> totalFemaleAllSkill += value
                                "star1Limit" -> totalStar1Limit += value
                                "star2Limit" -> totalStar2Limit += value
                                "star3Limit" -> totalStar3Limit += value
                                "star4Limit" -> totalStar4Limit += value
                                "star5Limit" -> totalStar5Limit += value
                                "star1Price" -> totalStar1Price += value
                                "star2Price" -> totalStar2Price += value
                                "star3Price" -> totalStar3Price += value
                                "star4Price" -> totalStar4Price += value
                                "star5Price" -> totalStar5Price += value
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 更新UI状态
    val ultimateSkills = UltimateSkillsState(
        stirfry = totalStirfry,
        boil = totalBoil,
        knife = totalKnife,
        fry = totalFry,
        bake = totalBake,
        steam = totalSteam,
        maleAllSkill = totalMaleAllSkill,
        femaleAllSkill = totalFemaleAllSkill
    )
    
    val recipeLimits = RecipeLimitsState(
        star1 = totalStar1Limit,
        star2 = totalStar2Limit,
        star3 = totalStar3Limit,
        star4 = totalStar4Limit,
        star5 = totalStar5Limit
    )
    
    val recipePrices = RecipePricesState(
        star1 = totalStar1Price,
        star2 = totalStar2Price,
        star3 = totalStar3Price,
        star4 = totalStar4Price,
        star5 = totalStar5Price
    )
    
    onLoadUltimate(ultimateSkills, recipeLimits, recipePrices)
}

/**
 * 清空修炼按钮逻辑
 */
private fun clearUltimateSkills(
    context: android.content.Context,
    onLoadUltimate: (UltimateSkillsState, RecipeLimitsState, RecipePricesState) -> Unit
) {
    val ultimateSkills = UltimateSkillsState()
    val recipeLimits = RecipeLimitsState()
    val recipePrices = RecipePricesState()
    
    // 清除本地存储
    val storage = UltimateDataStorage(context)
    storage.clearData()
    
    onLoadUltimate(ultimateSkills, recipeLimits, recipePrices)
}

/**
 * 判断技能是否为上场类技能（Partial）
 */
private fun isPartialSkill(skillId: Int): Boolean {
    return when (skillId) {
        // 场上所有厨师技法加成 - 上场类技能
        485, 486, 487, 488, 489, 490, 497, 498, 499 -> true
        // 其他技能默认为个人类技能
        else -> false
    }
}

/**
 * 根据技能ID获取技能加成值
 */
private fun getSkillValue(skillId: Int): Int {
    return when (skillId) {
        // +1 技能
        330, 331, 332, 333, 334, 335, 311, 321, 322, 323, 324 -> 1
        // +2 技能
        336, 337, 338, 339, 340, 341, 325 -> 2
        // +3 技能
        342, 343, 344, 345, 346, 347 -> 3
        // +4 技能
        348, 349, 350, 351, 352, 353 -> 4
        // +5% 技能
        315, 317, 318, 319 -> 5
        // +25 技能
        497, 498, 499 -> 25
        // +45 技能
        485, 486, 487 -> 45
        // 默认值
        else -> 1
    }
}

/**
 * 处理未知技能 - 通过技能数据自动判断技能类型和数值
 */
private fun processUnknownSkill(
    skillId: Int, 
    gameData: com.example.show_auto.data.GameData, 
    onSkillProcessed: (String, Int) -> Unit
) {
    // 查找技能数据
    val skill = gameData.skills.find { it.skillId == skillId }
    if (skill == null) {
        return
    }
    
    val desc = skill.desc
    
    // 根据技能描述判断类型和数值
    when {
        // 复合技能处理 - 同时影响售价和上限（支持任意顺序）
        (desc.contains("菜谱售价") || desc.contains("火菜谱售价")) &&
        (desc.contains("菜谱上限") || desc.contains("火菜谱上限")) -> {
            // 处理复合技能，不依赖顺序
            processCompositeSkill(desc, onSkillProcessed)
        }
        // 男厨师全技法
        desc.contains("男厨师全技法") -> {
            val value = extractNumberFromDesc(desc)
            onSkillProcessed("maleAllSkill", value)
        }
        // 女厨师全技法
        desc.contains("女厨师全技法") -> {
            val value = extractNumberFromDesc(desc)
            onSkillProcessed("femaleAllSkill", value)
        }
        // 菜谱上限
        desc.contains("菜谱上限") || desc.contains("火菜谱上限") -> {
            val value = extractNumberFromDesc(desc)
            when {
                desc.contains("1星") || desc.contains("1火") -> onSkillProcessed("star1Limit", value)
                desc.contains("2星") || desc.contains("2火") -> onSkillProcessed("star2Limit", value)
                desc.contains("3星") || desc.contains("3火") -> onSkillProcessed("star3Limit", value)
                desc.contains("4星") || desc.contains("4火") -> onSkillProcessed("star4Limit", value)
                desc.contains("5星") || desc.contains("5火") -> onSkillProcessed("star5Limit", value)
                desc.contains("所有") -> {
                    // 所有菜谱上限+1，分别加到各个星级
                    onSkillProcessed("star1Limit", value)
                    onSkillProcessed("star2Limit", value)
                    onSkillProcessed("star3Limit", value)
                    onSkillProcessed("star4Limit", value)
                    onSkillProcessed("star5Limit", value)
                }
                desc.contains("1至4火") -> {
                    // 1至4火菜谱上限+1
                    onSkillProcessed("star1Limit", value)
                    onSkillProcessed("star2Limit", value)
                    onSkillProcessed("star3Limit", value)
                    onSkillProcessed("star4Limit", value)
                }
                desc.contains("1至3火") -> {
                    // 1至3火菜谱上限+1
                    onSkillProcessed("star1Limit", value)
                    onSkillProcessed("star2Limit", value)
                    onSkillProcessed("star3Limit", value)
                }
            }
        }
        // 菜谱售价
        desc.contains("菜谱售价") || desc.contains("火菜谱售价") -> {
            val value = extractNumberFromDesc(desc)
            when {
                desc.contains("1星") || desc.contains("1火") -> onSkillProcessed("star1Price", value)
                desc.contains("2星") || desc.contains("2火") -> onSkillProcessed("star2Price", value)
                desc.contains("3星") || desc.contains("3火") -> onSkillProcessed("star3Price", value)
                desc.contains("4星") || desc.contains("4火") -> onSkillProcessed("star4Price", value)
                desc.contains("5星") || desc.contains("5火") -> onSkillProcessed("star5Price", value)
                // 处理复合技能，如"1星和2星菜谱售价各+3%"
                desc.contains("1星和2星") -> {
                    onSkillProcessed("star1Price", value)
                    onSkillProcessed("star2Price", value)
                }
            }
        }
        else -> {
            // 无法识别的技能类型，忽略
        }
    }
}

/**
 * 处理复合技能 - 同时影响售价和上限，支持任意顺序
 */
private fun processCompositeSkill(desc: String, onSkillProcessed: (String, Int) -> Unit) {
    // 提取售价数值
    val priceRegex = Regex("""售价\+(\d+)%""")
    val priceMatch = priceRegex.find(desc)
    val priceValue = priceMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0

    // 提取上限数值
    val limitRegex = Regex("""上限\+(\d+)""")
    val limitMatch = limitRegex.find(desc)
    val limitValue = limitMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0

    // 确定星级并应用加成
    when {
        desc.contains("1火") || desc.contains("1星") -> {
            if (priceValue > 0) onSkillProcessed("star1Price", priceValue)
            if (limitValue > 0) onSkillProcessed("star1Limit", limitValue)
        }
        desc.contains("2火") || desc.contains("2星") -> {
            if (priceValue > 0) onSkillProcessed("star2Price", priceValue)
            if (limitValue > 0) onSkillProcessed("star2Limit", limitValue)
        }
        desc.contains("3火") || desc.contains("3星") -> {
            if (priceValue > 0) onSkillProcessed("star3Price", priceValue)
            if (limitValue > 0) onSkillProcessed("star3Limit", limitValue)
        }
        desc.contains("4火") || desc.contains("4星") -> {
            if (priceValue > 0) onSkillProcessed("star4Price", priceValue)
            if (limitValue > 0) onSkillProcessed("star4Limit", limitValue)
        }
        desc.contains("5火") || desc.contains("5星") -> {
            if (priceValue > 0) onSkillProcessed("star5Price", priceValue)
            if (limitValue > 0) onSkillProcessed("star5Limit", limitValue)
        }
        // 处理多星级复合技能
        desc.contains("1星和2星") -> {
            if (priceValue > 0) {
                onSkillProcessed("star1Price", priceValue)
                onSkillProcessed("star2Price", priceValue)
            }
            if (limitValue > 0) {
                onSkillProcessed("star1Limit", limitValue)
                onSkillProcessed("star2Limit", limitValue)
            }
        }
        desc.contains("1至3火") || desc.contains("1至3星") -> {
            if (priceValue > 0) {
                onSkillProcessed("star1Price", priceValue)
                onSkillProcessed("star2Price", priceValue)
                onSkillProcessed("star3Price", priceValue)
            }
            if (limitValue > 0) {
                onSkillProcessed("star1Limit", limitValue)
                onSkillProcessed("star2Limit", limitValue)
                onSkillProcessed("star3Limit", limitValue)
            }
        }
        desc.contains("1至4火") || desc.contains("1至4星") -> {
            if (priceValue > 0) {
                onSkillProcessed("star1Price", priceValue)
                onSkillProcessed("star2Price", priceValue)
                onSkillProcessed("star3Price", priceValue)
                onSkillProcessed("star4Price", priceValue)
            }
            if (limitValue > 0) {
                onSkillProcessed("star1Limit", limitValue)
                onSkillProcessed("star2Limit", limitValue)
                onSkillProcessed("star3Limit", limitValue)
                onSkillProcessed("star4Limit", limitValue)
            }
        }
        desc.contains("所有") -> {
            if (priceValue > 0) {
                onSkillProcessed("star1Price", priceValue)
                onSkillProcessed("star2Price", priceValue)
                onSkillProcessed("star3Price", priceValue)
                onSkillProcessed("star4Price", priceValue)
                onSkillProcessed("star5Price", priceValue)
            }
            if (limitValue > 0) {
                onSkillProcessed("star1Limit", limitValue)
                onSkillProcessed("star2Limit", limitValue)
                onSkillProcessed("star3Limit", limitValue)
                onSkillProcessed("star4Limit", limitValue)
                onSkillProcessed("star5Limit", limitValue)
            }
        }
    }
}

/**
 * 从技能描述中提取数值
 */
private fun extractNumberFromDesc(desc: String, keyword: String = ""): Int {
    if (keyword.isNotEmpty()) {
        // 从复合技能中提取特定关键词后的数值
        val pattern = if (keyword == "售价") {
            Regex("""售价\+(\d+)%""")
        } else if (keyword == "上限") {
            Regex("""上限\+(\d+)""")
        } else {
            Regex("""\+(\d+)""")
        }
        val match = pattern.find(desc)
        return match?.groupValues?.get(1)?.toIntOrNull() ?: 1
    } else {
        // 提取第一个+数字
        val regex = Regex("""\+(\d+)""")
        val match = regex.find(desc)
        return match?.groupValues?.get(1)?.toIntOrNull() ?: 1
    }
}

/**
 * 获取厨师修炼技能描述
 */
private fun getChefSkillDescription(chef: Chef, skills: List<Skill>): String {
    if (!chef.hasUltimateSkill()) return "无修炼技能"
    val descs = chef.getAllUltimateSkills().mapNotNull { sid ->
        skills.find { it.skillId == sid }?.desc
    }
    return if (descs.isEmpty()) "无修炼技能" else descs.joinToString("\n")
}

/**
 * 统一的光环厨师筛选逻辑
 */
private fun isAuraChef(chef: Chef, skills: List<Skill>): Boolean {
    if (!chef.hasUltimateSkill()) return false
    
    val skillDesc = getChefSkillDescription(chef, skills)
    
    // 检查是否包含技法加成
    fun hasSkillBonus(desc: String): Boolean {
        return desc.contains("炒+") || desc.contains("煮+") || desc.contains("切+") || 
               desc.contains("炸+") || desc.contains("烤+") || desc.contains("蒸+") || 
               desc.contains("全技法+")
    }
    
    return (skillDesc.contains("场上所有厨师") || skillDesc.contains("下位上场厨师")) &&
           (!skillDesc.contains("售价") || hasSkillBonus(skillDesc)) &&
           !skillDesc.contains("采集") &&
           !skillDesc.contains("菜") &&
           !skillDesc.contains("鱼") &&
           !skillDesc.contains("肉") &&
           !skillDesc.contains("面")
}

